import { baseUrl } from '@/utils/http';
import { aesKey } from '@/utils/httpHead';
import { http } from "@/utils/http"
import dayjs from 'dayjs';
import crypto from 'crypto-js';
import { Base64 } from 'js-base64';

/**
 * 获取用户详细信息
 */
export const uploadFile = (file) => {
  return new Promise((resolve, reject) => {
    console.log('file', file);
    const token = uni.getStorageSync('token');
    uni.uploadFile({
      url: baseUrl + '/resource/oss/upload',
      filePath: file,
      name: 'file',
      header: {
          Clientid: aesKey,
          Authorization: `Bearer ${token}`,
          ContentType: 'multipart/form-data',
          'content-type': 'multipart/form-data',
          'content-language': 'zh_CN',
      },
      success: (uploadFileRes) => {
        console.log('uploadFileRes', uploadFileRes)
        if (uploadFileRes.statusCode === 200) {
          try {
            const { code, data } = JSON.parse(uploadFileRes.data) || {};
            if (code === 200) {
              resolve(data);
            } else {
              reject('1');
            }
          } catch {
            reject('2');
          }
        } else {
          reject('3');
        }
      },
      fail: (error) => {
        console.log('error', error)
         reject('4');
      }
    });
  })
}

export const uploadImg = ({
  imageUrl,
  token,
}) => {
  return new Promise(async (resolve, reject) => {
    const res = await http({
      url: '/oss/getConfig',
      method: 'POST',
      data: {
        bucket: '0563headurl',
      }
    }).catch(() => {
      reject('');
    });
    const { success, data } = res || {};
    const { accessKeyId, accessKeySecret, stsToken } = data || {};
    console.log('getConfig', res);
    if (success) {
      const computeSignature = (accessKeySecret, canonicalString) => {
        return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
      };
      const date = new Date();
      date.setHours(date.getHours() + 1);
      const policyText = {
        expiration: date.toISOString(),
        conditions: [
          // 限制上传大小。
          ["content-length-range", 0, 1024 * 1024 * 1024],
        ],
      };
      const policy = Base64.encode(JSON.stringify(policyText)); // policy必须为base64的string。
      const signature = computeSignature(accessKeySecret, policy);
      const imgTypeLs = imageUrl.split('.');
      const key = `${token || 'test'}/${dayjs().valueOf()}.${imgTypeLs[imgTypeLs.length - 1]}`;
      console.log({
        key,
        policy,
        OSSAccessKeyId: accessKeyId,
        signature,
        'x-oss-security-token': stsToken // 使用STS签名时必传。
      })
      const url = 'https://0563headurl.oss-cn-hangzhou.aliyuncs.com';
      wx.uploadFile({
        url,
        filePath: imageUrl,
        name: 'file',
        formData: {
          key,
          policy,
          OSSAccessKeyId: accessKeyId,
          signature,
          'x-oss-security-token': stsToken // 使用STS签名时必传。
        },
        success: (res) => {
          if (res.statusCode === 204) {
            console.log('上传成功', res);
            resolve(`${url}/${key}`);
          }
        },
        fail: err => {
          reject(err);
        }
      });
    } else {
      reject('');
    }
  })
};